<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Key } from '@element-plus/icons-vue'
import { useThemeStore } from '../../stores/theme'
import { authApi } from '../../api'

// 初始化主题
const themeStore = useThemeStore()
themeStore.initializeTheme()

const router = useRouter()

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 表单引用
const loginFormRef = ref()

// 加载状态
const loading = ref(false)

// 组件挂载时检查是否已登录
onMounted(() => {
  // 检查本地存储中是否有登录信息
  const savedUsername = localStorage.getItem('username')
  const savedPassword = localStorage.getItem('password')
  const rememberMe = localStorage.getItem('rememberMe') === 'true'
  
  if (rememberMe && savedUsername && savedPassword) {
    loginForm.username = savedUsername
    loginForm.password = savedPassword
    loginForm.rememberMe = true
  }
})

// 处理登录
const handleLogin = () => {
  loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      
      try {
        // 调用登录API
        const response = await authApi.login(
          loginForm.username,
          loginForm.password,
          loginForm.rememberMe
        )
        
        // 保存token
        localStorage.setItem('token', response.token)
        
        // 保存用户信息
        localStorage.setItem('userInfo', JSON.stringify(response.userInfo))
        
        // 保存登录信息
        if (loginForm.rememberMe) {
          localStorage.setItem('username', loginForm.username)
          localStorage.setItem('password', loginForm.password)
          localStorage.setItem('rememberMe', 'true')
        } else {
          localStorage.removeItem('username')
          localStorage.removeItem('password')
          localStorage.removeItem('rememberMe')
        }
        
        // 保存登录状态
        localStorage.setItem('isLoggedIn', 'true')
        
        ElMessage.success('登录成功')
        router.push('/dashboard')
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error(error.message || '用户名或密码错误')
      } finally {
        loading.value = false
      }
    }
  })
}

// 忘记密码
const handleForgotPassword = () => {
  ElMessage.info('请联系管理员重置密码')
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <img src="@/assets/logo.svg" alt="Logo" class="logo" />
        <h2>后台管理系统</h2>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
            size="large"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            size="large"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <div class="login-options">
          <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
          <el-button type="text" @click="handleForgotPassword">忘记密码？</el-button>
        </div>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-tips">
        <p>默认账号：admin</p>
        <p>默认密码：admin123</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, var(--el-color-primary-light-9), var(--el-color-primary-light-7));
  overflow: hidden;
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: var(--el-bg-color, #ffffff);
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 60px;
  height: 60px;
  margin-bottom: 10px;
}

.login-header h2 {
  font-size: 24px;
  color: var(--el-text-color-primary, #303133);
  margin: 0;
}

.login-form {
  margin-top: 20px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
}

.login-tips {
  margin-top: 20px;
  text-align: center;
  color: var(--el-text-color-secondary, #909399);
  font-size: 14px;
}

.login-tips p {
  margin: 5px 0;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .login-box {
    width: 90%;
    padding: 20px;
  }
}
</style>